<template>
  <div class="app-container">
    <el-form :inline="true" :model="search" class="mb8 search-bar">
      <el-form-item label="维修单号" class="field">
        <el-input v-model="search.workNo" placeholder="输入维修单号" clearable />
      </el-form-item>
      <el-form-item label="报修单号" class="field">
        <el-input v-model="search.reportNo" placeholder="输入报修单号" clearable />
      </el-form-item>
      <el-form-item label="状态" class="field">
        <el-select v-model="search.statusCode" placeholder="选择状态" clearable>
          <el-option label="待指派" value="PENDING_ASSIGN" />
          <el-option label="待执行" value="PENDING_EXEC" />
          <el-option label="执行中" value="IN_PROGRESS" />
          <el-option label="待料中" value="WAITING_MATERIAL" />
          <el-option label="已确认" value="CONFIRMED" />
          <el-option label="拒绝确认" value="REJECTED" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>


    <el-table v-loading="loading" :data="list" :fit="true" class="responsive-table">
      <el-table-column prop="workNo" label="维修单号" :min-width="160" show-overflow-tooltip resizable />
      <!-- 后端字段为 rptNo，这里统一显示为 reportNo（在getList中归一） -->
      <el-table-column prop="reportNo" label="报修单号" :min-width="180" show-overflow-tooltip resizable />
      <el-table-column prop="startTime" label="开始时间" :min-width="160" resizable />
      <el-table-column prop="endTime" label="结束时间" :min-width="160" resizable />
      <el-table-column :label="statusColumnLabel()" :min-width="110" resizable>
        <template slot-scope="scope">
          <el-tag :type="statusTypeDisplay(scope.row.statusCode)">{{ statusNameDisplay(scope.row.statusCode) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" :min-width="240" resizable>
        <template slot-scope="scope">
          <el-button type="text" class="op-link view" @click="handleView(scope.row)">查看</el-button>
          <el-button
            v-if="!isMinePage() && scope.row.statusCode === 'PENDING_ASSIGN'"
            type="text"
            class="op-link assign"
            @click="handleAssign(scope.row)"
          >指派</el-button>
          <el-button
            v-if="!isMinePage() && scope.row.statusCode === 'PENDING_CONFIRM'"
            type="text"
            class="op-link confirm"
            @click="handleConfirm(scope.row)"
          >确认</el-button>
          <el-button
            v-if="!isMinePage() && scope.row.statusCode === 'PENDING_CONFIRM'"
            type="text"
            class="op-link reject"
            @click="handleRejectConfirm(scope.row)"
          >拒绝确认</el-button>
          <el-button
            v-else-if="isMinePage() && (scope.row.statusCode === 'PENDING_EXEC' || scope.row.statusCode === 'IN_PROGRESS' || scope.row.statusCode === 'WAITING_MATERIAL')"
            type="text"
            class="op-link edit"
            @click="handleEdit(scope.row)"
          >执行维修</el-button>
          <el-button
            v-if="isMinePage() && (scope.row.statusCode === 'PENDING_EXEC' || scope.row.statusCode === 'IN_PROGRESS' || scope.row.statusCode === 'WAITING_MATERIAL' || scope.row.statusCode === 'EXTRA_PROCESSING')"
            type="text"
            class="op-link extra"
            @click="handleExtraProcessing(scope.row)"
          >{{ scope.row.statusCode === 'EXTRA_PROCESSING' ? '结束追加工' : '追加工' }}</el-button>
          <el-button
            v-if="isMinePage() && (scope.row.statusCode === 'PENDING_ASSIGN' || scope.row.statusCode === 'ASSIGNED')"
            type="text"
            class="op-link accept"
            @click="handleAccept(scope.row)"
          >接取</el-button>
          <el-button
            v-if="isMinePage() && scope.row.statusCode === 'PENDING_EXEC'"
            type="text"
            class="op-link return"
            @click="handleReturn(scope.row)"
          >退回</el-button>
          <el-button
            v-if="canDelete(scope.row)"
            type="text"
            class="op-link danger"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="query.pageNum"
      :limit.sync="query.pageSize"
      @pagination="getList"
    />

    <!-- 指派对话框 -->
    <el-dialog title="指派维修人员" :visible.sync="assignVisible" width="420px">
      <el-form :model="assignForm" :rules="assignRules" ref="assignForm" label-width="80px">
        <el-form-item label="维修单号">
          <el-input v-model="assignForm.workNo" disabled />
        </el-form-item>
        <el-form-item label="指派给" prop="assigneeId">
          <el-select v-model="assignForm.assigneeId" placeholder="请选择维修人员" filterable clearable style="width:100%">
            <el-option v-for="u in userOptions" :key="u.value" :label="u.label" :value="u.value" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="assignVisible=false">取 消</el-button>
        <el-button type="primary" @click="confirmAssign">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listWorks, updateWork } from '@/api/repair/work'
import request from '@/utils/request'
import store from '@/store'

export default {
  name: 'WorkIndex',
  data() {
    return {
      tab: 'all',
      loading: false,
      list: [],
      total: 0,
      query: { pageNum: 1, pageSize: 10 },
      search: { workNo: '', reportNo: '', statusCode: '' },
      // 指派对话框
      assignVisible: false,
      assignForm: { workNo: '', assigneeId: undefined },
      assignRules: {
        assigneeId: [
          { required: true, message: '请选择维修人员', trigger: 'change' }
        ]
      },
      userOptions: []
    }
  },
  created() {
    // 若当前路由是“我的维修”，切换到mine过滤（兼容不同菜单路径，如 /my-work 或 /system/my-work）
    const p = (this.$route && this.$route.path) || ''
    if (p.indexOf('/system/my-work') === 0 || p.indexOf('/my-work') === 0 || p.includes('my-work')) {
      this.tab = 'mine'
    }
    this.getList()
  },
  methods: {
    handleEdit(row) {
      // 编辑入口：跳转到维修详情（非只读），并带上当前workNo
      this.$router.push({ path: `/system/work/${row.workNo}`, query: { readonly: 0 } })
    },
    canDelete(row){
      const allowStatus = row.statusCode === 'DRAFT' || row.statusCode === 'CONFIRMED'
      const allowActor = this.isMinePage() || this.$auth.hasRole('admin') || this.$auth.hasPermi('system:work:remove')
      return allowStatus && allowActor
    },
    handleDelete(row){
      this.$confirm('确定要删除该维修单吗？此操作为逻辑删除。', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(()=>{
        // 复用更新接口做逻辑删除，具体以后端实现为准：例如 statusCode='DELETED' 或 isDelete=1
        updateWork({ ...row, isDelete: 1 }).then(()=>{
          this.$message.success('删除成功')
          this.getList()
        })
      }).catch(()=>{})
    },
    switchTab() {},
    handleQuery() {
      this.query.pageNum = 1
      this.getList()
    },
    resetQuery() {
      this.search = { workNo: '', reportNo: '', statusCode: '' }
      this.query.pageNum = 1
      this.getList()
    },
    getList() {
      this.loading = true
      const q = { ...this.query }
      const isMine = (this.$route && this.$route.path && (this.$route.path.indexOf('/system/my-work') === 0 || this.$route.path.indexOf('/my-work') === 0 || this.$route.path.includes('my-work')))
      if (isMine) q.mine = true
      if (this.search.workNo) q.workNo = this.search.workNo.trim()
      if (this.search.reportNo) q.rptNo = this.search.reportNo.trim()
      if (this.search.statusCode) q.statusCode = this.search.statusCode
      listWorks(q).then(res => {
        let rows = res.rows || []
        // 兼容不同后端字段：归一到 reportNo，用于显示与关联
        this.list = rows.map(it => ({
          ...it,
          reportNo: it.reportNo || it.rptNo || it.rptCode || it.reportCode
        }))
        this.total = res.total || 0
      }).finally(()=> this.loading = false)
    },
    handleView(row) {
      // 维修管理查看：只读模式
      try {
        sessionStorage.setItem('work-list-return', this.$route.fullPath || '/system/work/index')
      } catch(e) {}
      this.$router.push({ path: `/system/work/${row.workNo}`, query: { readonly: 1 } })
    },
    handleAssign(row) {
      this.assignForm = { workNo: row.workNo, assigneeId: row.assigneeId }
      this.assignVisible = true
      // 强制重新加载维修人员列表，确保只显示维修人员
      this.userOptions = [] // 清空现有选项
      // 仅拉取并展示"维修人员"角色（roleKey=maintenance_worker / 角色ID=4 / 角色名=维修人员）
      // 精准：调用"按角色已分配用户列表"，roleId=4（维修人员）
      request({ url: '/system/role/authUser/allocatedList', method: 'get', params: { pageNum: 1, pageSize: 200, roleId: 4 } })
        .then(res => {
          const rows = res.rows || []
          // rows 已为绑定角色4的用户列表
          const userMap = new Map()
          rows.forEach(u => {
            const nickName = u.nickName || u.userName
            if (nickName && !userMap.has(nickName)) userMap.set(nickName, u)
          })
          this.userOptions = Array.from(userMap.values()).map(u => ({ label: u.nickName || u.userName, value: u.userId }))
        })
        .catch(error => {
          console.error('加载维修人员列表失败:', error)
          this.$message.error('加载维修人员列表失败')
        })
    },
    confirmAssign() {
      this.$refs.assignForm.validate(valid => {
        if (valid) {
          const row = this.list.find(i => i.workNo === this.assignForm.workNo) || {}
          updateWork({ ...row, assigneeId: this.assignForm.assigneeId, statusCode: 'ASSIGNED' }).then(()=>{
            this.$message.success('指派成功')
            this.assignVisible = false
            this.getList()
          })
        } else {
          return false
        }
      })
    },
    handleConfirm(row) {
      this.$confirm('确认该维修已完成吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        updateWork({ ...row, statusCode: 'CONFIRMED' }).then(() => {
          this.$message.success('确认成功，已进入待承认状态')
          this.getList()
        })
      }).catch(() => {})
    },
    handleRejectConfirm(row) {
      this.$confirm('拒绝确认该维修单吗？拒绝后将重新分配给维修人员。', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 调用后端拒绝确认接口，逻辑与拒绝承认一致
        request({
          url: `/system/work/reject/${row.workNo}`,
          method: 'put'
        }).then(() => {
          this.$message.success('拒绝确认成功，已重新分配给维修人员')
          this.getList()
        }).catch(() => {
          this.$message.error('拒绝确认失败')
        })
      }).catch(() => {})
    },
    handleStart(row) {
      updateWork({ ...row, statusCode: 'IN_PROGRESS' }).then(()=>{
        this.$message.success('执行中')
        this.getList()
      })
    },
    handleAccept(row) {
      this.$confirm('确认接取该维修任务吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        updateWork({ ...row, statusCode: 'PENDING_EXEC' }).then(() => {
          this.$message.success('接取成功')
          this.getList()
        })
      }).catch(() => {
        // 用户取消，不做任何操作
      })
    },
    handleReturn(row) {
      this.$confirm('确认退回该维修任务吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        updateWork({ ...row, statusCode: 'PENDING_ASSIGN', assigneeId: null }).then(() => {
          this.$message.success('退回成功')
          this.getList()
        })
      }).catch(() => {
        // 用户取消，不做任何操作
      })
    },
    handleExtraProcessing(row) {
      // 判断当前是否处于追加工状态
      if (row.statusCode === 'EXTRA_PROCESSING') {
        // 结束追加工，恢复原来的状态
        const originalStatus = row.originalStatus || 'PENDING_EXEC';
        updateWork({ ...row, statusCode: originalStatus }).then(() => {
          this.$message.success('追加工结束，状态已恢复')
          this.getList()
        })
      } else {
        // 开始追加工，保存原始状态
        const originalStatus = row.statusCode;
        updateWork({ ...row, statusCode: 'EXTRA_PROCESSING', originalStatus }).then(() => {
          this.$message.success('开始追加工')
          this.getList()
        })
      }
    },
    // 维修管理默认状态名称
    statusName(code) {
      const map = {
        PENDING_ASSIGN: '待分配',
        ASSIGNED: '待接取',
        PENDING_EXEC: '待维修',
        IN_PROGRESS: '维修中',
        WAITING_MATERIAL: '待料中',
        PENDING_CONFIRM: '待确认',
        CONFIRMED: '已确认',
        REJECTED: '拒绝确认',
        EXTRA_PROCESSING: '追加工中'
      }
      return map[code] || code || ''
    },
    statusType(code) {
      const map = {
        PENDING_ASSIGN: 'warning',
        ASSIGNED: 'warning',
        PENDING_EXEC: 'info',
        IN_PROGRESS: 'primary',
        WAITING_MATERIAL: 'warning',
        PENDING_CONFIRM: 'warning',
        CONFIRMED: 'success',
        REJECTED: 'danger',
        EXTRA_PROCESSING: 'danger'
      }
      return map[code] || 'info'
    },
    // 我的维修显示"是否维修"
    statusNameDisplay(code) {
      const p = (this.$route && this.$route.path) || ''
      const isMine = p.indexOf('/system/my-work') === 0 || p.indexOf('/my-work') === 0 || p.includes('my-work')
      if (isMine) {
        const map = {
          PENDING_ASSIGN: '未接取',
          ASSIGNED: '未接取',
          PENDING_EXEC: '已接取',
          IN_PROGRESS: '维修中',
          WAITING_MATERIAL: '维修中',
          PENDING_CONFIRM: '待确认',
          CONFIRMED: '已确认',
          REJECTED: '未接取',
          EXTRA_PROCESSING: '追加工中'
        }
        return map[code] || '未接取'
      }
      return this.statusName(code)
    },
    statusTypeDisplay(code) {
      const p = (this.$route && this.$route.path) || ''
      const isMine = p.indexOf('/system/my-work') === 0 || p.indexOf('/my-work') === 0 || p.includes('my-work')
      if (isMine) {
        const map = {
          PENDING_ASSIGN: 'info',
          ASSIGNED: 'info',
          PENDING_EXEC: 'info',
          IN_PROGRESS: 'warning',
          WAITING_MATERIAL: 'warning',
          PENDING_CONFIRM: 'warning',
          CONFIRMED: 'success',
          REJECTED: 'info',
          EXTRA_PROCESSING: 'danger'
        }
        return map[code] || 'info'
      }
      return this.statusType(code)
    },
    statusColumnLabel() {
      const p = (this.$route && this.$route.path) || ''
      const isMine = p.indexOf('/system/my-work') === 0 || p.indexOf('/my-work') === 0 || p.includes('my-work')
      return isMine ? '是否维修' : '状态'
    },
    // 提供给模板直接判断
    isMinePage() {
      const p = (this.$route && this.$route.path) || ''
      return p.indexOf('/system/my-work') === 0 || p.indexOf('/my-work') === 0 || p.includes('my-work')
    }
  }
}
</script>

<style scoped>
  .search-bar {
    display: flex;
    flex-wrap: wrap;
    gap: 8px 16px;
  }
  .search-bar .field .el-input,
  .search-bar .field .el-select {
    width: 220px;
  }
  @media (max-width: 1366px) {
    .search-bar .field .el-input,
    .search-bar .field .el-select { width: 180px; }
  }
  @media (max-width: 1200px) {
    .search-bar .field .el-input,
    .search-bar .field .el-select { width: 160px; }
  }
  @media (max-width: 992px) {
    .search-bar .field .el-input,
    .search-bar .field .el-select { width: 140px; }
  }
  @media (max-width: 768px) {
    .search-bar .field .el-input,
    .search-bar .field .el-select { width: 100%; }
    .search-bar { flex-direction: column; }
  }
  .responsive-table .el-table__body-wrapper { overflow-x: auto; }
  .responsive-table .cell { white-space: nowrap; }
  .responsive-table .el-table__header-wrapper table,
  .responsive-table .el-table__body-wrapper table {
    table-layout: fixed; /* 让列在容器中均匀分配，结合 resizable 更稳定 */
    width: 100%;
  }
  .op-link { margin-right: 10px; }
  .op-link.view { color: #909399; }
  .op-link.assign { color: #409EFF; }
  .op-link.confirm { color: #67C23A; }
  .op-link.edit { color: #E6A23C; }
  .op-link.extra { color: #909399; font-weight: bold; }
  .op-link.accept { color: #67C23A; }
  .op-link.return { color: #F56C6C; }
  .op-link.danger { color: #F56C6C; }
  .op-link.execute { color: #67C23A; }
  .op-link.start { color: #E6A23C; display: none; }
  .op-link.finish { color: #67C23A; display: none; }
</style>
